---
title: "Module Functions"
description: "Module Functions in ReScript"
canonical: "/docs/manual/module-functions"
section: "Advanced Features"
order: 3
---

# Module Functions

Module functions can be used to create modules based on types, values, or functions from other modules.
This is a powerful tool that can be used to create abstractions and reusable code that might not be possible with functions, or might have a runtime cost if done with functions.

This is an advanced part of ReScript and you can generally get by with normal values and functions.

## Quick example

Next.js has a `useParams` hook that returns an unknown type,
and it's up to the developer in TypeScript to add a type annotation for the parameters returned by the hook.

```TS
const params = useParams<{ tag: string; item: string }>()
```

In ReScript we can create a module function that will return a typed response for the `useParams` hook.

<CodeTab labels={["ReScript", "JS Output"]}>
```res example
module Next = {
  // define our module function
  module MakeParams = (Params: { type t }) => {
    @module("next/navigation")
    external useParams: unit => Params.t = "useParams"
    /* You can use values from the function parameter, such as Params.t */
  }
}

module Component: {
@react.component
let make: unit => Jsx.element
} = {
// Create a module that matches the module type expected by Next.MakeParams
module P = {
type t = {
tag: string,
item: string,
}
}

// Create a new module using the Params module we created and the Next.MakeParams module function
module Params = Next.MakeParams(P)

@react.component
let make = () => {

// Use the functions, values, or types created by the module function
let params = Params.useParams()

  <div>
    <p>
      {React.string("Tag: " ++ params.tag /* params is fully typed! */)}
    </p>
    <p> {React.string("Item: " ++ params.item)} </p>
  </div>
  }
}

````
```js
// Generated by ReScript, PLEASE EDIT WITH CARE

import * as $$Navigation from "next/navigation";
import * as JsxRuntime from "react/jsx-runtime";

function MakeParams(Params) {
  return {};
}

var Next = {
  MakeParams: MakeParams
};

function Playground$Component(props) {
  var params = $$Navigation.useParams();
  return JsxRuntime.jsxs("div", {
              children: [
                JsxRuntime.jsx("p", {
                      children: "Tag: " + params.tag
                    }),
                JsxRuntime.jsx("p", {
                      children: "Item: " + params.item
                    })
              ]
            });
}

var Component = {
  make: Playground$Component
};

export {
  Next ,
  Component ,
}
/* next/navigation Not a pure module */

````

</ CodeTab>

## Sharing a type with an external binding

This becomes incredibly useful when you need to have types that are unique to a project but shared across multiple components.
Let's say you want to create a library with a `getEnv` function to load in environment variables found in `import.meta.env`.

```res
@val external env: 'a = "import.meta.env"

let getEnv = () => {
  env
}
```

It's not possible to define types for this that will work for every project, so we just set it as 'a and the consumer of our library can define the return type.

```res
type t = {"LOG_LEVEL": string}

let values: t = getEnv()
```

This isn't great and it doesn't take advantage of ReScript's type system and ability to use types without type definitions, and it can't be easily shared across our application.

We can instead create a module function that can return a module that has contains a `getEnv` function that has a typed response.

```res
module MakeEnv = (
  E: {
    type t
  },
) => {
  @val external env: E.t = "import.meta.env"

  let getEnv = () => {
    env
  }
}
```

And now consumers of our library can define the types and create a custom version of the hook for their application.
Notice that in the JavaScript output that the `import.meta.env` is used directly and doesn't require any function calls or runtime overhead.

<CodeTab labels={["ReScript", "JS Output"]}>
```res
module Env = MakeEnv({
	type t = {"LOG_LEVEL": string}
})

let values = Env.getEnv()

````
```js
var Env = {
  getEnv: getEnv
};

var values = import.meta.env;
````

</ CodeTab>

## Shared functions

You might want to share functions across modules, like a way to log a value or render it in React.
Here's an example of module function that takes in a type and a transform to string function.

```res
module MakeDataModule = (
  T: {
    type t
    let toString: t => string
  },
) => {
  type t = T.t
  let log = a => Console.log("The value is " ++ T.toString(a))

  module Render = {
    @react.component
    let make = (~value) => value->T.toString->React.string
  }
}
```

You can now take a module with a type of `t` and a `toString` function and create a new module that has the `log` function and the `Render` component.

<CodeTab labels={["ReScript", "JS Output"]}>
```res
module Person = {
  type t = { firstName: string, lastName: string } 
  let toString = person => person.firstName ++ person.lastName
}

module PersonData = MakeDataModule(Person)

````

```js
// Notice that none of the JS output references the MakeDataModule function

function toString(person) {
  return person.firstName + person.lastName;
}

var Person = {
  toString: toString
};

function log(a) {
  console.log("The value is " + toString(a));
}

function Person$MakeDataModule$Render(props) {
  return toString(props.value);
}

var Render = {
  make: Person$MakeDataModule$Render
};

var PersonData = {
  log: log,
  Render: Render
};
````

</CodeTab>

Now the `PersonData` module has the functions from the `MakeDataModule`.

<CodeTab labels={["ReScript", "JS Output"]}>
```res
@react.component
let make = (~person) => {
  let handleClick = _ => PersonData.log(person)
  <div>
    {React.string("Hello ")}
    <PersonData.Render value=person />
    <button onClick=handleClick>
      {React.string("Log value to console")}
    </button>
  </div>
}
```
```js
function Person$1(props) {
  var person = props.person;
  var handleClick = function (param) {
    log(person);
  };
  return JsxRuntime.jsxs("div", {
              children: [
                "Hello ",
                JsxRuntime.jsx(Person$MakeDataModule$Render, {
                      value: person
                    }),
                JsxRuntime.jsx("button", {
                      children: "Log value to console",
                      onClick: handleClick
                    })
              ]
            });
}
```
</CodeTab>

## Dependency injection

Module functions can be used for dependency injection.
Here's an example of injecting in some config values into a set of functions to access a database.

<CodeTab labels={["ReScript", "JS Output"]}>
```res
module type DbConfig = {
  let host: string
  let database: string
  let username: string
  let password: string
}

module MakeDbConnection = (Config: DbConfig) => {
type client = {
write: string => unit,
read: string => string,
}
@module("database.js")
external makeClient: (string, string, string, string) => client = "makeClient"

let client = makeClient(Config.host, Config.database, Config.username, Config.password)
}

module Db = MakeDbConnection({
let host = "localhost"
let database = "mydb"
let username = "root"
let password = "password"
})

let updateDb = Db.client.write("new value")

````
```js
// Generated by ReScript, PLEASE EDIT WITH CARE

import * as DatabaseJs from "database.js";

function MakeDbConnection(Config) {
  var client = DatabaseJs.makeClient(Config.host, Config.database, Config.username, Config.password);
  return {
          client: client
        };
}

var client = DatabaseJs.makeClient("localhost", "mydb", "root", "password");

var Db = {
  client: client
};

var updateDb = client.write("new value");

export {
  MakeDbConnection ,
  Db ,
  updateDb ,
}
/* client Not a pure module */
````

</CodeTab>
